#!/usr/bin/env python
import argparse
from MyPylike import MyNewLike

def cli():
    parser = argparse.ArgumentParser(prefix_chars='-+',
             description='This is a binned likelihood analysis tools based on Fermi pyLikelihood package')
    parser.add_argument("srcMaps", type=str, help='Source Maps')
    parser.add_argument("expCube", type=str, help='Live Time Cube')
    parser.add_argument("binnedExpMap", type=str, help='Exposure Cube')
    parser.add_argument("srcModel", type=str, help='model.xml')
    parser.add_argument("irfs", type=str, help='IRFs')

    parser.add_argument("-centerSrc", type=str, default=None, help='The name of the center source')
    parser.add_argument("+edispon", action='store_true', default=None, help='The flag to enable edisp.')
    parser.add_argument("+accurateTS", action='store_true', default=False, help='The flag to refit to get the TS value of ctr src')
    parser.add_argument("+edispoff", action='store_true', default=None, help='The flag to disable edisp.')
    parser.add_argument('-edispbins', type=int, default=-2, help='the extra ebins added (default=-2)')
    parser.add_argument("-emin", type=float, default=None, help='Use Max(emin_set, emin_data) as minimum energy in the fit')
    parser.add_argument("-emax", type=float, default=None, help='Use Min(emax_set, emax_data) as maximum energy in the fit')
    parser.add_argument("-saveFolder", type=str, default='./', help='Where to save output files')

    parser.add_argument("-twopasses", action='store_false', default=True, help='run two fit or not')
    parser.add_argument("-fitalg1", type=str, default='DRMNFB', choices=['DRMNFB', 'DRMNGB', 'MINUIT', 'NewMinuit'],
                        help='The first fit algorithm')
    parser.add_argument("-fitalg2", type=str, default='MINUIT', choices=['DRMNFB', 'DRMNGB', 'MINUIT', 'NewMinuit'],
                        help='The second fit algorithm')
    parser.add_argument("-tol1", type=float, default=0.001, help='The tolerance of the first fit')
    parser.add_argument("-tol2", type=float, default=1.e-5, help='The tolerance of the second fit')
    parser.add_argument("-modelout1", type=str, default='model_pyLike_pass1.xml', help='The output xml model of the first run')
    parser.add_argument("-modelout2", type=str, default='model_pyLike_pass2.xml', help='The output xml model of the second run')

    parser.add_argument("+NoUpperLimit", action='store_true', default=False, help='Whether to calculate UpperLimit')
    parser.add_argument("+NotTuneScale", action='store_true', default=False, help='Whether to optimize the scale after the 1st pass')
    parser.add_argument("-ULTSLimit", type=float, default=10., help='UpperLimit will be calculated when Center source whose TS lower than ULTSLimit')
    parser.add_argument("-ULemin", type=float, default=None, help='The emin[MeV] of the upper limit flux')
    parser.add_argument("-ULemax", type=float, default=None, help='The emax[MeV] of the upper limit flux')

    parser.add_argument("+freezeWeak", action='store_true', default=False, help='Whether to freeze weak sources before fit in pass2')
    parser.add_argument("-distLimit", type=float, default=0., help='The sources outside distLimit will be optimized')
    parser.add_argument("-TSLimit0", type=float, default=1., help='The sources whose TS lower than TSLimit0 will be deleted')
    parser.add_argument("-TSLimit1", type=float, default=10., help='The sources whose TS lower than TSLimit1 will be totally fixed in spectrum')
    parser.add_argument("-TSLimit2", type=float, default=25., help='The sources whose TS lower than TSLimit2 will be fixed in index')

    parser.add_argument("+likeprofile", action='store_true', default=False, help='Whether to run profile likelihood')
    parser.add_argument("+profile_fit", action='store_true', default=False, help='Whether to fit during profile likelihood')
    parser.add_argument("-profile_out", type=str, default='loglike_profile_pyLike.dat', help='the name of loglike_profile.dat file')
    parser.add_argument("-profile_maxdlike", type=float, default=20., help='The maximum change of delta loglikelihood')
    parser.add_argument("-profile_maxdlikebin", type=float, default=0.1, help='The maximum bin width of dloglike profile')
    parser.add_argument("-profile_fluxmin", type=float, default=None, help='The minimum flux in the profile likelihood')
    parser.add_argument("-profile_fluxmax", type=float, default=None, help='The maximum flux in the profile likelihood')

    parser.add_argument("-resultsdata", type=str, default='results_pyLike.dat', help='the name of result.dat file')
    #parser.add_argument("-countsspec", type=str, default='counts_spectra_pyLike.fits', help='the name of counts_spectrum.fits file')
    parser.add_argument("-countsspec", type=str, default=None, help='the name of counts_spectrum.fits file')
    parser.add_argument("-covardata", type=str, default='covariance_pyLike.dat', help='the name of covariance.dat file')
    args = parser.parse_args()

    if args.edispon is None and args.edispoff is None:
        edisp_flag = None
    elif args.edispon:
        edisp_flag = True
    else:
        edisp_flag = False

    MyNewLike.binLikeCLI(srcMaps=args.srcMaps, expCube=args.expCube, binnedExpMap=args.binnedExpMap,
                         srcModel=args.srcModel, irfs=args.irfs, edispon=edisp_flag, edisp_bins=args.edispbins,
                         centerSrc=args.centerSrc, ApproxTS=not args.accurateTS,
                         emin=args.emin, emax=args.emax, saveFolder=args.saveFolder,
                         twopasses=args.twopasses, fitalg1=args.fitalg1, fitalg2=args.fitalg2, tol1=args.tol1, tol2=args.tol2,
                         modelout1=args.modelout1, modelout2=args.modelout2,
                         NoUpperLimit=args.NoUpperLimit, ULTSLimit=args.ULTSLimit, ULemin=args.ULemin, ULemax=args.ULemax,
                         freezeWeak=args.freezeWeak, tuneScale=not args.NotTuneScale,
                         TSLimit0=args.TSLimit0, TSLimit1=args.TSLimit1, TSLimit2=args.TSLimit2, distLimit=args.distLimit,
                         likeprofile=args.likeprofile, profile_fit=args.profile_fit, profile_out=args.profile_out,
                         profile_maxdlike=args.profile_maxdlike, profile_maxdlikebin=args.profile_maxdlikebin,
                         profile_fluxmin=args.profile_fluxmin, profile_fluxmax=args.profile_fluxmax,
                         results_data=args.resultsdata, counts_spec=args.countsspec, covar_data=args.covardata
                        )

if __name__ == '__main__': cli()
